package edu.purdue.cs505;

public class ReliableChannelTestSuite
{

   private static String SOCKET_IP = "127.0.0.1";
   static int portA = 4445;
   static int portB = 4446;
   static ReliableChannelImpl nodeA;
   static ReliableChannelImpl nodeB;

   public static void main(String[] args)
   {
      initialize();
      simpleTest();
      resendTest();
      manyMessagesTest();

      nodeA.halt();
      nodeB.halt();
   }

   private static void initialize()
   {
      nodeA = new ReliableChannelImpl(SOCKET_IP, portA);
      nodeB = new ReliableChannelImpl(SOCKET_IP, portB);
      nodeA.init(SOCKET_IP, portB);
      nodeB.init(SOCKET_IP, portA);
      nodeA.rlisten(new PrintingReceiver());
      nodeB.rlisten(new PrintingReceiver());
   }

   private static void simpleTest()
   {
      sendMessage(nodeA, "simple test from A", false);
      sendMessage(nodeB, "simple test from B", false);

      try
      {
         Thread.sleep(1000);
      }
      catch (InterruptedException e)
      {
         e.printStackTrace();
      }
   }

   private static void resendTest()
   {
      sendMessage(nodeA, "resend test from A", true);

      try
      {
         Thread.sleep(6000);
      }
      catch (InterruptedException e)
      {
         e.printStackTrace();
      }
   }

   private static void manyMessagesTest()
   {
      for (int i = 0; i < 100; i++)
      {
         sendMessage(nodeA, "from A " + i, false);
         sendMessage(nodeB, "from B " + i, false);
      }

      try
      {
         Thread.sleep(10000);
      }
      catch (InterruptedException e)
      {
         e.printStackTrace();
      }
   }

   private static void sendMessage(ReliableChannelImpl nodeFrom, String message, boolean fail)
   {
      Message m = new Message();
      m.setContents(message);
      if (!fail)
         nodeFrom.rsend(m);
      else
         nodeFrom.rsendFail(m);
   }

}
